package com.agrishare.repository;

import java.util.List;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import com.agrishare.entity.Category;
import com.agrishare.entity.Post;
import com.agrishare.entity.PostStatus;
import com.agrishare.entity.PostType;
import com.agrishare.entity.User;

@Repository
public interface PostRepository extends JpaRepository<Post, Long> {

    Page<Post> findByStatus(PostStatus status, Pageable pageable);

    Page<Post> findByAuthor(User author, Pageable pageable);

    Page<Post> findByCategoryId(Long categoryId, Pageable pageable);

    Page<Post> findByType(PostType type, Pageable pageable);
    // 或者使用@Query注解自定义查询
    @Query("SELECT p FROM Post p WHERE p.status = 'PENDING'")
    Page<Post> findPendingPosts(Pageable pageable);

    @Query("SELECT p FROM Post p WHERE p.status = 'APPROVED' ORDER BY p.isTop DESC, p.createdAt DESC")
    Page<Post> findApprovedPostsOrderByTopAndTime(Pageable pageable);

    @Query("SELECT p FROM Post p WHERE p.status = 'APPROVED' AND (p.title LIKE %:keyword% OR p.content LIKE %:keyword%)")
    Page<Post> findByKeyword(@Param("keyword") String keyword, Pageable pageable);

    @Query("SELECT p FROM Post p WHERE p.status = 'APPROVED' ORDER BY p.viewCount DESC")
    List<Post> findHotPosts(Pageable pageable);

    @Query("SELECT p FROM Post p WHERE p.status = 'APPROVED' AND p.isEssence = true ORDER BY p.createdAt DESC")
    List<Post> findEssencePosts(Pageable pageable);
    @Query("SELECT p FROM Post p WHERE p.isPinned = true ORDER BY p.createdAt DESC")
    Page<Post> findPinnedPosts(Pageable pageable);

    @Query("SELECT p FROM Post p WHERE p.isFeatured = true ORDER BY p.createdAt DESC")
    Page<Post> findFeaturedPosts(Pageable pageable);

    List<Post> findByAuthorAndStatus(User author, PostStatus status);

    Page<Post> findByIsApprovedTrueOrderByCreatedAtDesc(Pageable pageable);
    Page<Post> findByCategoryAndIsApprovedTrueOrderByCreatedAtDesc(Category category, Pageable pageable);
    Page<Post> findByAuthorOrderByCreatedAtDesc(User author, Pageable pageable);

}
